package com.andrew.servlet;

import java.io.IOException;
import java.util.Properties;
import java.util.Random;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendEmailServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		
		//生成注册码
		Random random=new Random();
		String emailKey=String.valueOf(random.nextInt(999999-100000+1)+100000);
		//保存cookie
		Cookie cookie = new Cookie("emailKey",emailKey);
		cookie.setMaxAge(60);
		resp.addCookie(cookie);
		
		//获取用户邮箱
		String customerEmail=req.getParameter("email");
		
		//服务器的设置
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");

		//账号和密码
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 163账号和密码
				return new PasswordAuthentication("zwq957283329@163.com", "zwq957283329");
			}
		};

		// 与163服务器建立连接：Session
		Session session = Session.getDefaultInstance(props, authenticator);

		//编写邮件：Message
		Message message = new MimeMessage(session);
		try {
			// 发件人
			message.setFrom(new InternetAddress("zwq957283329@163.com"));
			// 收件人
			message.setRecipient(RecipientType.TO, new InternetAddress(customerEmail));
			// 主题
			message.setSubject("QweasBookStore注册验证码");
			// 内容
			message.setContent(emailKey, "text/html;charset=UTF-8");

			// 3 将消息进行发送：Transport
			Transport.send(message);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
